package org.sabayframework.cluster.impl.felix;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.felix.framework.Felix;
import org.apache.felix.framework.util.FelixConstants;
import org.apache.felix.framework.util.StringMap;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.Constants;
/*
modular extensibility: 
	how to automatically deploy bundles at runtime
	how to obtain current bundle and it's dependencies 
 * */
public class Main  {

	static Felix felix;
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws Exception {
		startFramework("bundle", "sabay");
	}

//	private static List<String> scanDirectory(File directory) {
//		ArrayList<String> bundles= new ArrayList<String>();
//		if (directory.exists()) {
//			File[] files = directory.listFiles();
//			for (File file : files) {
//				String fileName=file.getName();
//				if(file.isFile() && fileName.toLowerCase().endsWith(".jar")){
//					bundles.add(file.getAbsolutePath());
//				}
//			}
//		}
//		return bundles;
//	}

	private static void startFramework(String bundleLocation, String cacheLocation){
        final File cachedir =new File(cacheLocation);
//        final File bundledir =new File(bundleLocation);
//        List<String> bundles = scanDirectory(bundledir);
//        StringBuilder sb=new StringBuilder();
//        for(String bundle:bundles){
//        	sb.append("file:").append(bundle).append(' ');
//        }
        StringMap configMap = new StringMap(false);
        configMap.put(FelixConstants.LOG_LEVEL_PROP, "4");
        //if(sb.length()>0)configMap.put(AutoActivator.AUTO_START_PROP + ".1", sb.toString());
        configMap.put(Constants.FRAMEWORK_STORAGE, cachedir.getAbsolutePath());

        // Create list to hold custom framework activators.
        List<BundleActivator> list = new ArrayList<BundleActivator>();
        // Add activator to process auto-start/install properties.
        //list.add(new AutoActivator(configMap));
        // Add our own activator.
        list.add(new Activator());
        // Add our custom framework activators to the configuration map.
        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);

        try
        {
            // Now create an instance of the framework.
            felix = new Felix(configMap);
            felix.start();
        }
        catch (Exception ex)
        {
            System.err.println("Could not create framework: " + ex);
            ex.printStackTrace();
            System.exit(-1);
        }
		
	}
}
